/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef OHMW_INTERFACES_CXX_NODE_H
#define OHMW_INTERFACES_CXX_NODE_H

#include "framework/c++/bincode/Decoder.h"
#include "framework/c++/bincode/Encoder.h"
#include <cstdint>
#include <functional>
#include <string_view>
#include <vector>

namespace OHOS {
namespace OHMW {
class Node {
public:
    enum class Type : uint8_t {
        DORA = 0,
        ROS,
        ROS2,
    };

    Node(std::string_view node_path, Type type);
    Node(const Node&) = delete;
    Node& operator=(const Node&) = delete;
    ~Node();

    int32_t Send(std::string_view path, const uint8_t* data, uint32_t len);
    int32_t Recv(std::string_view path, uint8_t* data, uint32_t *len, uint32_t timeout);
    int32_t OnRecv(std::string_view path, std::function<void(uint8_t*, uint32_t)> callback);

    template<typename T>
    int32_t SendMsg(std::string_view path, const T& msg) {
        std::vector<uint8_t> buffer;
        DefaultEncoder encoder(sizeof(uint32_t));
        msg.Encode(encoder, buffer);
        DefaultEncoder().Put(buffer, static_cast<uint32_t>(buffer.size()));
        return Send(path, buffer.data(), buffer.size());
    }

    template<typename T>
    int32_t RecvMsg(std::string_view path, T& msg, uint32_t timeout) {
        return -1;
    }

    template<typename T>
    int32_t OnRecvMsg(std::string_view path, std::function<void(T&)> callback) {
        return OnRecv(path, [callback](uint8_t* data, uint32_t len) {
            // TODO: optimize this
            DefaultDecoder decoder(sizeof(uint32_t));
            T msg;
            if (!T::Decode(decoder, std::vector<uint8_t>(data, data + len), msg)) {
                return;
            }
            callback(msg);
        });
    }

    // TODO
    int32_t Channel(std::string_view node_path);

private:
    void *node_ = nullptr;
};
}
}

#endif
